const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/jwt');

// 定义白名单路由
const whiteList = [
  '/users/login',
  '/users/register',
  '/favicon.ico'
];

function *verifyToken(next) {
  // 检查是否在白名单中
  if (whiteList.includes(this.path)) {
    yield next;
    return;
  }

  try {
    // 获取 token
    const authorization = this.headers.authorization;
    if (!authorization) {
      this.status = 401;
      this.body = { status: 0, message: '请先登录' };
      return;
    }

    const token = authorization.split(' ')[1];
    if (!token) {
      this.status = 401;
      this.body = { status: 0, message: '无效的token格式' };
      return;
    }

    // 验证 token
    const decoded = jwt.verify(token, jwtConfig.secret);
    
    // 将用户信息存储到 state 中
    this.state.user = decoded;
    
    yield next;
  } catch (err) {
    this.status = 401;
    this.body = {
      status: 0,
      message: err.name === 'TokenExpiredError' ? 'token已过期，请重新登录' : 'token无效，请重新登录'
    };
  }
}

module.exports = verifyToken;